package com.icss.th.search.servlet;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.icss.th.db.pojo.PageInfo;
import com.icss.th.fulltext.FullTextSearchFactory;
import com.icss.th.fulltext.IFullTextSearch;
import com.icss.th.fulltext.pojo.SearchResult;

/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/adsearch")
public class AdvanceSearchServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String subjectId = request.getParameter("subjectId");
		String type = request.getParameter("type");
		String keyword = URLDecoder.decode(request.getParameter("keyword"), "UTF-8");
		String unkeyword = URLDecoder.decode(request.getParameter("unkeyword"), "UTF-8");
		String pnum = request.getParameter("pnum");
		int startYear = 0;
		int endYear = 0;
		String sYear = request.getParameter("sYear");
		if(!"".equals(sYear) && sYear != null){
			startYear = Integer.valueOf(sYear);
		}
		String eYear = request.getParameter("eYear");
		if(!"".equals(eYear) && eYear != null){
			endYear = Integer.valueOf(eYear);
		}
		
		PageInfo pi = new PageInfo();
		if (pnum != null && !"".equals(pnum))
		{
			pi.setPageNum(Integer.valueOf(pnum));
		}
		
		List<SearchResult> list = null;
		long beginTime = new Date().getTime();
		IFullTextSearch search = FullTextSearchFactory.getInstance();
		if (search != null)
		{
			list = search.advanceSearch("0".equals(subjectId)? null : subjectId, type, keyword, unkeyword, startYear, endYear, pi);
		}
		float spendTime = (new Date().getTime() - beginTime)/1000f;
		
		request.setAttribute("list", list);
		request.setAttribute("pageInfo", pi);
		request.setAttribute("spendTime", String.valueOf(spendTime));
		
		request.setAttribute("subjectId", subjectId);
		request.setAttribute("type", type);
		request.setAttribute("keyword", keyword);
		request.setAttribute("unkeyword", unkeyword);
		request.setAttribute("startYear", startYear);
		request.setAttribute("endYear", endYear);
		
		request.getRequestDispatcher("/list.jsp").forward(request, response);
	}
}
